import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import socket from '@/utils/socket'
import { ElMessage } from 'element-plus'
import { playMessageSound } from '@/utils/sound'

export const useMessageStore = defineStore('message', () => {
    // 状态
    const chatList = ref([]) // 聊天列表
    const currentChatMessages = ref([]) // 当前聊天的消息列表
    const currentChatImKey = ref(null) // 当前聊天的imKey
    const unreadCount = ref(0) // 未读消息总数

    // 计算属性
    const sortedChatList = computed(() => {
        return [...chatList.value].sort((a, b) => {
            return b.lastMessage?.time - a.lastMessage?.time
        })
    })

    // 移除所有socket监听器
    const removeSocketListeners = () => {
        socket.off('chatList');
        socket.off('chatMsg');
    }

    // 方法
    // 初始化socket监听
    const initSocketListeners = () => {
        // 先移除之前的监听器，防止重复绑定
        removeSocketListeners();

        // 监听聊天列表
        socket.on('chatList', (response) => {
            if (response.code === 200) {
                chatList.value = response.data.map(chat => ({
                    ...chat,
                    unreadCount: chat.unreadCount || 0
                }))
                calculateUnreadCount()
            }
        })

        // 监听新消息
        socket.on('chatMsg', (response) => {
            console.log('收到新消息事件', response)
            if (response.code === 200) {
                const { data } = response
                // 播放提示音
                playMessageSound()
                // 构造消息数据格式，与历史消息格式保持一致
                const messageData = {
                    _id: data.id,
                    user: data.user,
                    toUser: data.toUser,
                    msg: {
                        from: data.msg.from,
                        fromName: data.msg.fromName,
                        fromAvatar: data.msg.fromAvatar,
                        fromType: data.msg.fromType,
                        to: data.msg.to,
                        toName: data.msg.toName,
                        toAvatar: data.msg.toAvatar,
                        toType: data.msg.toType,
                        content: data.msg.content,
                        contentType: data.msg.contentType,
                        time: data.msg.time,
                        msgKey: data.msg.msgKey
                    },
                    read: false, // 如果是当前聊天，则标记为已读
                    msgKey: data.msgKey,
                    createTime: new Date().toISOString()
                }
                console.log('收到新消息，完整消息数据：', messageData)
                console.log('当前消息列表长度：', currentChatMessages.value.length)

                // 更新聊天列表中的最后一条消息
                updateChatListLastMessage(messageData)

                // 如果是当前聊天，则添加到消息列表
                const isCurrentChat = messageData.user === currentChatImKey.value ||
                    messageData.toUser === currentChatImKey.value
                console.log('当前聊天imKey：', currentChatImKey.value)
                console.log('是否当前聊天：', isCurrentChat)

                if (isCurrentChat) {
                    console.log('添加到当前聊天消息列表')
                    currentChatMessages.value = [...currentChatMessages.value, messageData]
                    console.log('更新后消息列表长度：', currentChatMessages.value.length)
                }

                // 更新未读数
                calculateUnreadCount()
            }
        })
    }

    // 获取聊天列表
    const getChatList = () => {
        socket.emit('chatList')
    }

    // 获取历史消息
    const getChatHistory = (imKey, page = 1, pageSize = 20) => {
        currentChatImKey.value = imKey
        return new Promise((resolve, reject) => {
            socket.emit('chatHistory', { imKey, page, pageSize }, (response) => {
                if (response.code === 200) {
                    const messages = [...response.data].reverse()
                    if (page === 1) {
                        // 首次加载，直接替换
                        currentChatMessages.value = messages
                    } else {
                        // 加载更多，添加到列表开头
                        currentChatMessages.value = [...messages, ...currentChatMessages.value]
                    }
                    resolve(response.data)
                } else {
                    ElMessage.error(response.message || '获取历史消息失败')
                    reject(response)
                }
            })
        })
    }

    // 发送消息
    const sendMessage = (imKey, content, type = 'text') => {
        return new Promise((resolve, reject) => {
            socket.emit('chatMsg', { to: imKey, content, contentType: type }, (response) => {
                if (response.code === 200) {
                    // 构建消息数据，使用与 ChatMessages.vue 相同的格式
                    const messageData = {
                        _id: response.data.msgKey,
                        user: response.data.from,
                        toUser: response.data.to,
                        msg: {
                            from: response.data.from,
                            fromName: response.data.fromName,
                            fromAvatar: response.data.fromAvatar,
                            fromType: response.data.fromType,
                            to: response.data.to,
                            toName: response.data.toName,
                            toAvatar: response.data.toAvatar,
                            toType: response.data.toType,
                            content: response.data.content || content,
                            contentType: response.data.contentType || type,
                            time: response.data.time || new Date().getTime(),
                            msgKey: response.data.msgKey
                        },
                        read: true,
                        msgKey: response.data.msgKey,
                        createTime: response.data.time ? new Date(response.data.time).toISOString() : new Date().toISOString()
                    }

                    console.log('发送消息，服务器响应：', response.data)
                    console.log('构建的消息数据：', messageData)

                    // 添加到当前聊天消息列表
                    currentChatMessages.value = [...currentChatMessages.value, messageData]

                    // 使用统一的方法更新聊天列表的最后一条消息
                    updateChatListLastMessage(messageData)

                    resolve(response.data)
                } else {
                    ElMessage.error(response.message || '发送消息失败')
                    reject(response)
                }
            })
        })
    }

    // 更新聊天列表中的最后一条消息
    const updateChatListLastMessage = (messageData) => {
        console.log('更新最后一条消息，查找聊天：', messageData.user, messageData.toUser)
        const chatIndex = chatList.value.findIndex(
            chat => chat.imKey === messageData.user || chat.imKey === messageData.toUser
        )
        console.log('找到的聊天索引：', chatIndex)
        if (chatIndex > -1) {
            console.log('更新前的最后一条消息：', chatList.value[chatIndex].lastMessage)
            chatList.value[chatIndex].lastMessage = messageData.msg
            console.log('更新后的最后一条消息：', chatList.value[chatIndex].lastMessage)

            // 如果不是当前聊天的消息，且是对方发送的，则增加未读数
            if (!messageData.read && messageData.user === chatList.value[chatIndex].imKey) {
                chatList.value[chatIndex].unreadCount = (chatList.value[chatIndex].unreadCount || 0) + 1
                console.log('更新未读数：', chatList.value[chatIndex].unreadCount)
            }
        } else {
            // 如果是新聊天，重新请求聊天列表
            getChatList()
        }
    }

    // 计算未读消息总数
    const calculateUnreadCount = () => {
        unreadCount.value = chatList.value.reduce((total, chat) => {
            return total + (chat.unreadCount || 0)
        }, 0)
        console.log('总未读数：', unreadCount.value)
    }

    // 标记消息为已读
    const markMessagesAsRead = (imKey) => {
        // 更新消息列表中的消息状态
        currentChatMessages.value = currentChatMessages.value.map(msg => {
            if (msg.user === imKey) {
                return { ...msg, read: true }
            }
            return msg
        })

        // 更新聊天列表中的未读数
        const chatIndex = chatList.value.findIndex(chat => chat.imKey === imKey)
        if (chatIndex > -1) {
            chatList.value[chatIndex].unreadCount = 0
        }

        // 重新计算总未读数
        calculateUnreadCount()
    }

    return {
        chatList,
        currentChatMessages,
        currentChatImKey,
        unreadCount,
        sortedChatList,
        initSocketListeners,
        removeSocketListeners,
        getChatList,
        getChatHistory,
        sendMessage,
        markMessagesAsRead
    }
}) 